package com.sxjh.controller.ny;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.cglib.CglibUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sxjh.annotation.UserLog;
import com.sxjh.common.*;
import com.sxjh.config.Authorization;
import com.sxjh.entity.Ic;
import com.sxjh.entity.WagonNumber;
import com.sxjh.entity.param.*;
import com.sxjh.entity.result.IcListResult;
import com.sxjh.entity.result.IcOneResult;
import com.sxjh.service.IcLogService;
import com.sxjh.service.IcService;
import com.sxjh.service.WagonNumberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * IC卡列表  前端控制器
 * 权限配置
 * insert into permissions
 * (name, guard_name, description) values
 * ('ic.index', 'api', 'IC卡 列表'),
 * ('ic.query', 'api', 'IC卡 查询'),
 * ('ic.bind', 'api', 'IC卡 绑定'),
 * ('ic.unbind', 'api', 'IC卡 解绑'),
 * </p>
 *
 * @author zixin
 * @since 2021-06-06
 */
@RestController
@RequestMapping("/ic")
@Api(tags = "IC卡")
public class IcController extends BaseController {

    @Autowired
    private IcService icService;

    @Autowired
    private IcLogService icLogService;

    @Autowired
    private WagonNumberService wagonNumberService;

    @ApiOperation("列表")
    @GetMapping
    @Authorization("ic.list")
    Result<ZPage<IcListResult>> list(@Validated IcListParam param) {
        IPage iPage = getIPage(param);
        iPage = icService.list(iPage, param);
        ZPage<IcListResult> zPage = copyPage(iPage, IcListResult::new);
        return Result.ok(zPage);
    }

    @ApiOperation("补卡查询列表")
    @GetMapping("/select")
    Result<List<IcListResult>> select(@Validated IcListParam param) {
        List<IcListResult> list = icService.select(param);
        return Result.ok(list);
    }

    @ApiOperation("查询")
    @GetMapping("/{id}")
    @Authorization("ic.query")
    Result<IcOneResult> query(@PathVariable Integer id) {
        Ic ic = icService.getById(id);
        if (ic == null) return Result.err("该ID不存在");
        IcListParam param = new IcListParam();
        param.setId(id);
        IPage iPage = getIPage(param);
        iPage = icService.list(iPage, param);
        IcOneResult one = CglibUtil.copy(ic, IcOneResult.class);
        if (iPage != null && CollUtil.isNotEmpty(iPage.getRecords())) {
            one = CglibUtil.copy(iPage.getRecords().get(0), IcOneResult.class);
        }
        return Result.ok(one);
    }

    @ApiOperation("查看编辑/绑定")
    @PostMapping("/bind")
    @Authorization("ic.bind")
    @UserLog(desc = "内部倒运-IC卡绑定", roleCode = "ic.bind")
    Result<String> bind(@RequestBody @Validated IcBindParam param) {
        synchronized (icService) {
            Ic ic = icService.getById(param.getId());
            if (ic == null) return Result.err("卡号不存在");
            //if (ic.getWagonNumberId() != null) return Result.err("该卡号已绑定其他车");
            /*int count2 = icService.count(new LambdaQueryWrapper<Ic>().eq(Ic::getWagonNumberId, param.getVehId()));
            if (count2 > 0) return Result.err("该车辆已被其他卡号绑定");*/
            ic.setWagonNumberId(param.getVehId());
            WagonNumber wagonNumber = wagonNumberService.getById(ic.getWagonNumberId());
            if (null == wagonNumber) return Result.err("车号ID不存在");
            // 保存IC卡记录
            icLogService.saveLog(param.getVehId(), param.getId(), null, null, Constant.UNLOAD_BIND);
            String record = String.format("车牌号：%s，IC卡印刷编号：%s", wagonNumber.getNumber(), ic.getPrinting());
            return icService.updateById(ic) ? Result.ok(record) : Result.err("绑定失败");
        }
    }

    @ApiOperation("解绑")
    @PostMapping("/unbind")
    @Authorization("ic.unbind")
    @UserLog(desc = "内部倒运-IC卡解绑", roleCode = "ic.unbind")
    Result<String> unbind(@RequestBody @Validated IdParam param) {
        synchronized (icService) {
            Ic ic = icService.getById(param.getId());
            if (ic == null) return Result.err("卡号不存在");
            if (ic.getWagonNumberId() <= 0) return Result.err("未绑定");
            WagonNumber wagonNumber = wagonNumberService.getById(ic.getWagonNumberId());
            // 保存IC卡记录
            icLogService.saveLog(ic.getWagonNumberId(), param.getId(), null, null, Constant.UNLOAD_UN_BING);
            String record = String.format("车牌号：%s，IC卡印刷编号：%s", wagonNumber == null ? "" : wagonNumber.getNumber(), ic.getPrinting());
            return icService.update(new LambdaUpdateWrapper<Ic>()
                    .set(Ic::getCreatedAt, null)
                    .set(Ic::getWagonNumberId, null)
                    //.set(Ic::getTare, "")
                    //.set(Ic::getTareImg, "")
                    //.set(Ic::getTareImgTwo, "")
                    .eq(Ic::getId, param.getId())) ? Result.ok(record) : Result.err("解绑失败");
        }
    }

    @ApiOperation("录入IC卡")
    @PostMapping("/entering")
    @Authorization("ic.entering")
    @UserLog(desc = "内部倒运-录入IC卡", roleCode = "ic.entering")
    Result<String> entering(@RequestBody @Validated IcEnteringParam param) {
        Ic ic = CglibUtil.copy(param, Ic.class);
        int count = icService.count(new LambdaQueryWrapper<Ic>().eq(Ic::getNumber, param.getNumber()));
        if (count > 0) {
            return Result.err("卡号已存在!");
        }
        try {
            icService.save(ic);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Result.err("卡号或印刷编号已存在");
        }
        // 清空称重时间
//        icService.update(new LambdaUpdateWrapper<Ic>()
//                .eq(Ic::getId, ic.getId())
//                .set(Ic::getCreatedAt, null));
//        String record = String.format("IC卡印刷编号：%s", ic.getPrinting());
        return Result.ok("");
    }

    @ApiOperation("删除")
    @GetMapping(value = "/delete/{id}")
    @Authorization("ic.del")
    @UserLog(desc = "内部倒运-删除IC卡", roleCode = "ic.del")
    public Result<Object> delete(@PathVariable("id") String id) {
        Ic ic = icService.getById(id);
        if (Objects.nonNull(ic) && ic.getWagonNumberId() != null) {
            int count = wagonNumberService.count(new LambdaQueryWrapper<WagonNumber>().eq(WagonNumber::getId, ic.getWagonNumberId()));
            if (count > 0) return Result.err("请先与车辆解绑才能删除");
        }
        icService.removeById(id);
        return Result.ok(HttpStatus.OK);
    }

    @ApiOperation("补卡")
    @PostMapping(value = "/new-card")
    @UserLog(desc = "内部倒运-补卡IC卡", roleCode = "ic.entering")
    public Result<Object> newCard(@RequestBody @Validated IcNewCardParam param) throws ResultException {
        if (param.getId() == null || param.getNewId() == null) {
            throw new ResultException("IC卡id不可为空");
        }
        Ic currentIc = icService.getById(param.getId());
        Ic newIc = icService.getById(param.getNewId());
        if (Objects.nonNull(currentIc) && Objects.nonNull(newIc)) {
            newIc.setFee(param.getFee());
            newIc.setRemark(param.getRemark());
            newIc.setWagonNumberId(currentIc.getWagonNumberId());
            icService.updateById(newIc);
            icService.removeById(currentIc.getId());
        }
        return Result.ok(HttpStatus.OK);
    }


}